package utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Description: 读取年份的工具类
 * @Author: syh
 * @Date: 2024/01/21/11:12
 */
public class YearUtil {

    /**
     * 配置文件存在就读取配置文件，不存在的话读取前后俩年
     * @return
     * @throws Exception
     */
    public static Object[] getYear() {
        String yearConfig=null;
        if(PathUtil.getJarPath().contains("jar")) {
            yearConfig = PathUtil.getJarPath().replaceAll("[a-z_]+.jar", "") + "yearConfig.txt";
        }else{
            yearConfig = PathUtil.getJarPath()+ "yearConfig.txt";
        }
        if(yearConfig.startsWith("/")){
            yearConfig = yearConfig.substring(1);
        }

        File yearFile = new File(yearConfig);
        if(!yearFile.exists()){
            SimpleDateFormat format = new SimpleDateFormat("yyyy");
            Integer year = Convert.toInt(format.format(new java.util.Date()));

            String[] strArr = new String[]{(year+2+""),(year+1+""),(year+""),(year-1+""),(year-2+"")};
            return new Object[]{strArr,year+""};
        }

        JSONObject yearObj = JSONUtil.parseObj(FileUtil.readString(yearConfig, "utf-8"));
        JSONArray yearArr = yearObj.getJSONArray("yearArr");
        String defaultYear = yearObj.getStr("defaultYear");
        List<String> yearList = yearArr.toList(String.class);
        String[] strArr = new String[yearList.size()];
        for (int i = 0 ; i < yearList.size(); i++) {
            strArr[i] = yearList.get(i);
        }
        
        return new Object[]{ strArr,defaultYear};
    }

    public static void main(String[] args) {
        System.out.println(ArrayUtil.join(getYear(),","));
    }
}
